package com.authapi.sample.api.utils;

import com.authapi.sample.api.model.Tree.Itree;

import java.util.ArrayList;
import java.util.List;

public class ListToTreeConverter<T extends Itree<T>> {
    public List<T> recursionMethod(List<T> treeList) {
        List<T> trees = new ArrayList<>();
        for (T tree : treeList) {
            // 找出父节点
            if (null == tree.getParentId()) {
                // 调用递归方法填充子节点列表
                trees.add(findChildren(tree, treeList));
            }
        }
        return trees;
    }

    /**
     * 递归方法
     * @param tree 父节点对象
     * @param treeList 所有的List
     * @return
     */
    public T findChildren(T tree, List<T> treeList) {
        for (T node : treeList) {
            if (tree.getId().equals(node.getParentId())) {
                if (tree.getChildren() == null) {
                    tree.setChildren(new ArrayList<>());
                }
                // 递归 调用自身
                tree.getChildren().add(findChildren(node, treeList));
            }
        }
        return tree;
    }
}
